#!/usr/bin/env python

import cgi

# From http://www.wsgi.org/wsgi/Specifications/handling_post_forms
def is_post_request(environ):
	if(environ['REQUEST_METHOD'].upper() != 'POST'): return False
	content_type = environ.get('CONTENT_TYPE', 'application/x-www-form-urlencoded')
	return (content_type.startswith('application/x-www-form-urlencoded')
			or content_type.startswith('multipart/form-data'))

def is_get_request(environ):
	if(environ['REQUEST_METHOD'].upper() != 'GET'): return False
	return True

class InputProcessed(object):
	def read(self, *args):
		raise EOFError('The wsgi.input stream has already been consumed')
	readline = readlines = __iter__ = read

def get_post_form(environ):
	input = environ['wsgi.input']
	post_form = environ.get('wsgi.post_form')
	if (post_form and post_form[0] is input):
		return post_form[2]
	# This must be done to avoid a bug in cgi.FieldStorage
	environ.setdefault('QUERY_STRING', '')
	fs = cgi.FieldStorage(fp=input,
							environ=environ,
							keep_blank_values=1)
	new_input = InputProcessed()
	post_form = (new_input, input, fs)
	environ['wsgi.post_form'] = post_form
	environ['wsgi.input'] = new_input
	return fs

def get_get_form(environ):
	if(not 'QUERY_STRING' in environ): return False
	fs = cgi.FieldStorage(	environ=environ,
							keep_blank_values=1)
	environ['wsgi.get_form'] = fs
	return fs
	
# Here will follow some classes that I want to test - so they could be unuseful sometimes
class Former:
	"""
	Provides user authentication and session management
	"""

	def __init__(self, app, **args):
		"""
		app - WSGI application to execute 
		login - link to login form
		Additional arguments:
		idLen - Session key len in bits (default 160)
		expire - Session expiration time in seconds (default 60)
		"""
		self.app = app

	def __call__(self, environ, start_response):
		if(is_post_request(environ)):
			get_post_form(environ)
		elif(is_get_request(environ)):
			get_get_form(environ)
		return self.app(environ, start_response)
